package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wfyn
 * @date 2023/10/6
 */
@Service
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatProperties weChatProperties;


    /**
     * 使用微信登录进行用户认证
     *
     * @param userLoginDTO 包含用户登录信息的DTO对象
     * @return 用户对象
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {

        String openId = getOpenId(userLoginDTO.getCode());


        // 如果openid为null，抛出登录失败异常
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 根据openid查询用户信息
        User user = userMapper.getByOpenId(openId);

        // 如果用户不存在，创建新用户并插入数据库
        if (user == null) {
                 user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);

        }

        return user;
    }
    /**
     * 从微信登录响应中提取openid
     *
     * @param code code
     * @return openid字符串，如果未找到则返回null
     */
    private String getOpenId(String code) {
        // 构建请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        // 发起HTTP GET请求获取响应
        String s = HttpClientUtil.doGet(WX_LOGIN, paramMap);

        // 解析响应JSON
        JSONObject jsonObject = JSON.parseObject(s);

        // 获取openid

        return jsonObject.getString("openid");
    }

}
